<template>
  <div class="update-avatar">
    <!-- 图片标签 -->
    <img :src="imgData" ref="imgPre" />
    <div class="toolbar">
      <span @click="$emit('onClose')">取消</span>
      <span @click="doUpdate">完成</span>
    </div>
  </div>
</template>

<script>
// 导入cropperjs 样式 和 js
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

// 导入api接口
import { updatePhoto } from '@/api/user.js'

export default {
  name: '',
  props: {
    // 要剪裁的图片数据
    imgData: {
      type: [String, Object],
      required: true
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  created() {},
  // 当组件 挂载到 dom树中后执行
  mounted() {
    // a.获取 图片 dom 对象
    const image = this.$refs.imgPre
    // b.创建 裁剪插件对象，并传入 图片dom和配置信息，这样就可以看到裁剪插件了
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
  },
  methods: {
    // 1.确定修改图片-------------------
    doUpdate() {
      // 获取 裁剪后的 图片数据
      this.cropper.getCroppedCanvas().toBlob(async (imgBlob) => {
        try {
          const fd = new FormData()
          fd.append('photo', imgBlob)
          const res = await updatePhoto(fd)
          this.$emit('onClose')
          this.$emit('onChangePhoto', res.data.data.photo)
          console.log(res)
          this.$toast.success('上传成功啦~')
        } catch (error) {
          this.$toast.fail('上传失败咯~')
        }
      })
    }
  },
  computed: {},
  watch: {},
  components: {}
}
</script>

<style lang="less" scoped>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  img {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
